import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

export const useAppStore = defineStore('app', () => {
  // 状态
  const settings = ref({
    refreshInterval: 2000,
    darkMode: false,
    cpuThreshold: 80,
    memoryThreshold: 80,
    diskThreshold: 90
  })
  
  const systemInfo = ref(null)
  const systemLoad = ref(null)
  const performanceHistory = ref({
    cpu: [],
    memory: [],
    network: []
  })

  // 加载设置
  async function loadSettings() {
    try {
      const result = await window.electron.loadSettings()
      if (result) {
        settings.value = result
        applyTheme(result.darkMode)
        return true
      }
      return false
    } catch (error) {
      console.error('加载设置失败:', error)
      ElMessage.error('加载设置失败')
      return false
    }
  }

  // 保存设置
  async function saveSettings(newSettings) {
    try {
      const success = await window.electron.saveSettings(newSettings)
      if (success) {
        settings.value = newSettings
        applyTheme(newSettings.darkMode)
        ElMessage.success('设置保存成功')
        return true
      }
      ElMessage.error('设置保存失败')
      return false
    } catch (error) {
      console.error('保存设置失败:', error)
      ElMessage.error('保存设置失败')
      return false
    }
  }

  // 应用主题
  function applyTheme(isDark) {
    const html = document.documentElement
    if (isDark) {
      html.classList.add('dark')
      html.setAttribute('data-theme', 'dark')
    } else {
      html.classList.remove('dark')
      html.setAttribute('data-theme', 'light')
    }
  }

  // 更新系统信息
  function updateSystemInfo(info) {
    systemInfo.value = info
  }

  // 更新系统负载
  function updateSystemLoad(load) {
    systemLoad.value = load
  }

  // 更新性能历史
  function updatePerformanceHistory(history) {
    performanceHistory.value = history
  }

  // 监听设置更新
  if (window.electron) {
    window.electron.onSettingsUpdated((newSettings) => {
      settings.value = newSettings
      applyTheme(newSettings.darkMode)
    })
  }

  return {
    settings,
    systemInfo,
    systemLoad,
    performanceHistory,
    loadSettings,
    saveSettings,
    updateSystemInfo,
    updateSystemLoad,
    updatePerformanceHistory
  }
}) 